/**
 * Created by xz on 2017/7/4.
 */
"use strict";

//点击展示所有评论
var flag = true;
var pb = {};
$(document).on('click','.commentCount',function () {
    if(flag) {
        $(this).parent().css('height','auto');
        $(this).siblings(".subComment").css('display','block');
        flag = false;
    } else {
        $(this).parent().css('height','70px');
        $(this).siblings(".subComment").css('display','none');
        $(this).parent().children(".subComment:first-child").css('display','block');
        flag = true;
    }
});

$(document).on('click', '.photo-container, .caption', function (e) {
    var target = $(e.target);
    if(target.closest("img").length === 0 && target.closest("video").length == 0){
        pb.close();
    };
})
    .on('click', '.weui-photo-browser-modal video', function () {
        if($(this).get(0).paused) {
            $(this).get(0).play()
        }else{
            $(this).get(0).pause()
        }
    })
    .on('click', '.resource img, .resource video, .share-resource img, .share-resource video', function() {
    pb.open(parseInt($(this).attr('data-index')));
});


function ajax(url, param, type) {
    // 利用了jquery延迟对象回调的方式对ajax封装，使用done()，fail()，always()等方法进行链式回调操作
    return $.ajax({
        url: url,
        data: param || {},
        type: type || 'GET',
        dataType: "json"
    });
};


/*
 * 获取用户信息
 */
var str=location.href;
var idList1 = str.split('?')[1];
if(idList1) {
    var id = idList1.split('=')[1];
};
var url = '';
if(str.indexOf('localhost') > -1) {
    url = "";
}else {
    url = window.location.host;
    // url = "http://120.77.0.27/community/forummessage/getForumMsgDetail?forumMsgId="
}
ajax(url+"/community/forummessage/getForumMsgDetail?forumMsgId="+id).done(function (resp) {
    var data = resp;
    // var data = $.parseJSON(resp);
    console.log(data);
    if(data.success) {
        //用户头像
        // $('.userImg img').attr('src',data.data.userHeadUrl);
        $('.userImg').css('backgroundImage', 'url('+data.data.userHeadUrl+')');
        $('.userName').html(data.data.nickName);
        $(".desc .address").html(data.data.postionLabel === null ? '' : data.data.postionLabel);
        //标签加内容
        var text = '';
        if(data.data.listForummessagelabel.length>0){
            //内容
            for(var i = 0; i< data.data.listForummessagelabel.length; i++) {
                text += "<span style='color: blueviolet'>#"+data.data.listForummessagelabel[i].labelDescribe+"#</span>";
            }
        }
        text += data.data.msgContent;
        $('.text p').html(text);
        // $('.text p').html("<span style='color: blueviolet'>#"+data.data.msgStruct+"#</span>"+data.data.msgContent);
        $(".message .desc .time").html(timeChange(data.data.createDate));
        //分享次数
        if(data.data.shareCount > 0) {
            $('.shareNum').css('display', 'block');
            $('.shareNum').html(data.data.shareCount);
        };

        getData(data, 'resource');

        //存在源帖则渲染分享信息
        if(data.data.sourceId) {
            $(".shareContent").css('display', 'block');
            ajax(url+"/community/forummessage/getForumMsgDetail?forumMsgId="+data.data.sourceId).done(function (resb) {
                var shareData = resb.data;
                //用户头像
                $('.shareContent .userImg img').attr('src',shareData.userHeadUrl);
                $('.shareContent .userName').html(shareData.nickName);
                $(".shareContent .desc .address").html(shareData.postionLabel === null ? '' : shareData.postionLabel);
                //标签加内容
                var text = '';
                if(shareData.listForummessagelabel.length>0){
                    //内容
                    for(var i = 0; i< shareData.listForummessagelabel.length; i++) {
                        text += "<span style='color: blueviolet'>#"+shareData.listForummessagelabel[i].labelDescribe+"#</span>";
                    }
                }
                text += shareData.msgContent;
                $('.shareContent .text p').html(text);
                // $('.text p').html("<span style='color: blueviolet'>#"+data.data.msgStruct+"#</span>"+data.data.msgContent);
                $(".shareContent .message .desc .time").html(timeChange(shareData.createDate));
                getData(resb, 'share-resource');
            });
        };

        //点赞记录数
        if(data.data.listForumlikespointrecord.length > 0 ) {
            $(".likeCount").css('display', 'block');
            $(".message .likeCount .first").html("<svg class='icon1' aria-hidden='true'><use xlink:href='#icon-zan2'></use></svg><span class='number'>"+data.data.listForumlikespointrecord.length+"</span>个赞");
        }
        // else if(data.data.listForumlikespointrecord.length === 1){
        //     $(".message .likeCount .first").html("<svg class='icon1' aria-hidden='true'><use xlink:href='#icon-zan2'></use></svg><span class='likeName'>"+data.data.listForumlikespointrecord[0].userNickName+"</span>点赞");
        // }
        else{
            $(".likeCount").css('display', 'none');
            $(".message .likeCount .first").html('');
        };
        if(data.data.listForumcomment.length > 0) {
            $('.likeCount .commentNum').css('display', 'block');
            $('.likeCount .commentNum').html(data.data.listForumcomment.length+'次点赞');
        };

        //如果有评论
        if(data.data.listForumcomment.length>0){
            $(".commentBody").remove();
            $(".comment .commentNum").html("当前"+data.data.listForumcomment.length+"条评论");
            var comment = data.data.listForumcomment;
            for(var i = 0;i < comment.length; i++){
                var temp = $("#commentTemp").clone().html();
                //评论用户昵称
                var html = temp.replace("用户昵称01", comment[i].userNickname);
                //评论时间
                html = html.replace("10分钟前", timeChange(comment[i].createDate));
                //评论内容
                html = html.replace("content1", comment[i].content);
                //点赞数
                // html = html.replace("likeNum", comment[i].likesCount == null?0:comment[i].likesCount);
                //评论图片
                if(comment[i].commentPicUrl) {
                    html = html.replace("defaultImg",comment[i].commentPicUrl);
                } else {
                    html = html.replace("commentImg","commentImg hidden");
                }
                //如果存在子评论
                if(comment[i].listForumcomment.length>0){
                    var commentList = comment[i].listForumcomment;
                    var text = '';
                    for(var j = 0;  j< commentList.length; j++) {
                        text += "<div class='subComment'><p class='title'>"+commentList[j].userNickname+"回复"+comment[i].userNickname+"</p><p class='text'>"+commentList[j].content+"</p></div>";
                    };
                    text += "<p class='commentCount'>共"+commentList.length+"条回复<i class='icon iconfont1 icon-xiangyou'></i></p>"
                    html = html.replace("回复",text);
                }else {
                    html = html.replace("reply","reply hidden");
                    // $('.reply').remove();
                };
                $('.empty').before(html);
                var height = $(".commentBody").eq(i).find(".subComment:first-child").height();
                if(height) {
                    $(".commentBody").eq(i).find(".reply").height(height+30)
                };
            };
        }else{
            $('.comment').empty();
            $('.comment').append("<div class='NoComment'><img src='image/empty.jpg'></div><p class='NoCommetText'>还没有人评论，有些寂寞</p>");
        }
        $("body").css('display','block');
    }else {
        // alert(data.message);
        $("body").css('display','block');
        $("body").html("<div style='text-align: center;margin-top: 2rem;'><img src='http://youdoneed-test.oss-cn-shenzhen.aliyuncs.com/165fa66uhrq1srgzj37b.jpg' alt=''><p style='margin-top: 0.5rem;font-size: 32px;'>获取信息失败，请稍后再试</p></div>");
    }
}).fail(function(err) {
    console.log(err);
});
// 渲染数据
function getData(data, el) {
    //是否存在音频，视频图片资源
    if(data.data.listForummediaresource.length>0) {
        var resource = data.data.listForummediaresource;
        $('.'+el+' .song').empty();
        // $('.other').empty();
        var arr = [];
        for(var i = 0; i< resource.length; i++) {
            //    如果有音频，则不存在图片加视频
            if(resource[i].songUrl){
                $('.'+el+' .song').append("<div><a href="+resource[i].songUrl+">"+resource[i].singerName+"-"+resource[i].songName+"</a></div>")
            }else {
                //存在图片与视频
                arr.push(resource[i]);
            }
        };
        var items = [];
        for(var j = 0; j < arr.length; j++) {
            if(arr[j].mediaType === 'picture') {
                items.push("<div style='width: 100%;height: 40%;text-align: center;'><img src=" + arr[j].imageUrl + " alt=''></div>");
            }else {
                items.push("<div style='width: 100%;height: 40%;text-align: center;'><video style='width: 100%;height: 100%;'><source src=" + arr[j].videoUrl + "  type='video/mp4' /><source src=" + arr[j].videoUrl + "  type='video/ogg' /></video></div>");
            }
        }
        // 调用图片浏览插件
        pb = $.photoBrowser({
            items: items,
            onSlideChange: function(index) {
                $(".swiper-pagination-bullets").html(index + 1 +'/' + items.length)
            },

            onOpen: function() {
                $(".swiper-pagination-bullets").html(this.activeIndex + 1 +'/' + items.length);
            },
            onClose: function() {
                console.log("onClose", this);
            }
        });

        $('.'+el+' .other').empty();
        $('.'+el+' .first').empty();
        if(data.data.imageLayoutType === 0 || data.data.imageLayoutType === 1) {
            $('.'+el+' .other').append("<div class='weui-flex__item'>"+tempAdd(arr[0], 0, '100%') +"</div>");
        }else if(data.data.imageLayoutType === 2) {
            $('.'+el+' .other').append("<div class='weui-flex__item'>"+tempAdd(arr[0], 0, '100%') +"</div>");
            $('.'+el+' .other').append("<div class='weui-flex__item'>"+tempAdd(arr[1], 1, '100%') +"</div>");
        }else if(data.data.imageLayoutType === 3) {
            $('.'+el+' .other').append("<div class='weui-flex__item' style='margin-right: 2%'>"+tempAdd(arr[0], 0, '100%') +"</div>");
            $('.'+el+' .other').append("<div class='weui-flex__item'>"+tempAdd(arr[1], 1, '100%') +"</div>");
        }else if(data.data.imageLayoutType === 4) {
            $('.'+el+' .other').append("<div class='weui-flex__item'>"+tempAdd(arr[0], 0, '49%', '2%') +tempAdd(arr[1], 1, '49%') +"</div>");
            // $('.'+el+' .other').append("<div class='weui-flex__item'></div>");
        }else if(data.data.imageLayoutType === 5) {
            $('.'+el+' .other').append("<div style='width: 66%;margin-right: 1.5%;'>"+tempAdd(arr[0], 0, '100%') +"</div>");
            $('.'+el+' .other').append("<div class='weui-flex__item'>"+tempAdd(arr[1], 1, '100%') +tempAdd(arr[2], 2, '100%') +"</div>");
        }else if(data.data.imageLayoutType === 6) {
            $('.'+el+' .first').append("<div class='weui-flex__item'>"+tempAdd(arr[0], 0, '100%') +"</div>");
            $('.'+el+' .other').append("<div class='weui-flex__item'>"+tempAdd(arr[1], 1, '50%') +tempAdd(arr[2], 2, '50%') +"</div>");
        }else if(data.data.imageLayoutType === 7) {
            if(arr[0].mediaDirection === 2 && arr[1].mediaDirection === 2 && arr[2].mediaDirection === 2) {
                $('.'+el+' .other').append("<div class='weui-flex__item'>"+tempAdd(arr[0], 0, '32%', '2%') +tempAdd(arr[1], 1, '32%', '2%')+tempAdd(arr[2], 2, '32%') +"</div>");
            }else {
                $('.'+el+' .other').append("<div style='width: 65%;margin-right: 2%'>"+tempAdd(arr[0], 0, '100%') +"</div>");
                $('.'+el+' .other').append("<div class='weui-flex__item'>"+tempAdd(arr[1], 1, '49%', '2%') +tempAdd(arr[2], 2, '49%') +"</div>");
            }
        }else if(data.data.imageLayoutType === 8) {
            $('.'+el+' .first').append("<div class='weui-flex__item'>"+tempAdd(arr[0], 0, '100%') +"</div>");
            $('.'+el+' .other').append("<div class='weui-flex__item'>"+tempAdd(arr[1], 1, '32%', '2%') +tempAdd(arr[2], 2, '32%', '2%')+tempAdd(arr[3], 3, '32%') +"</div>");
        }else if(data.data.imageLayoutType === 9) {
            $('.'+el+' .other').append("<div style='width: 74%;margin-right: 2%;'>"+tempAdd(arr[0], 0, '100%') +"</div>");
            $('.'+el+' .other').append("<div class='weui-flex__item'>"+tempAdd(arr[1], 1, '100%')+tempAdd(arr[2], 2, '100%') +tempAdd(arr[3], 3, '100%') +"</div>");
        }else if(data.data.imageLayoutType === 10) {
            $('.'+el+' .first').append("<div class='weui-flex__item'>"+tempAdd(arr[0], 0, '49%', '2%') +tempAdd(arr[1], 1, '49%') +"</div>");
            $('.'+el+' .other').append("<div class='weui-flex__item'>"+tempAdd(arr[2], 2, '32%', '2%') +tempAdd(arr[3], 3, '32%', '2%') +tempAdd(arr[4], 4, '32%') +"</div>");
        }else if(data.data.imageLayoutType === 100) {
            $('.'+el+' .first').append("<div class='weui-flex__item'>"+tempAdd(arr[0], 0, '49%', '2%') +tempAdd(arr[1], 1, '49%') +"</div>");
            $('.'+el+' .other').append("<div class='weui-flex__item'>"+tempAdd(arr[2], 2, '32%', '2%') +tempAdd(arr[3], 3, '32%', '2%') +tempAdd(arr[4], 4, '32%') +"</div>");
        }

        // $('.'+el+' .other .first').empty();
        // $('.'+el+' .other .second').empty();
        // if(arr.length === 1) {
        //     $('.'+el+' .other .first').append("<div class='weui-flex__item'><img src="+arr[0].imageUrl+" style='width:100%;'></div>");
        // }else if(arr.length === 2) {
        //     $('.'+el+' .other .first').append("<div class='weui-flex__item'><img src="+arr[0].imageUrl+" style='width:99%;'></div><div class='weui-flex__item'><img src="+arr[0].imageUrl+" style='width:99%;margin-left:1%;'></div>");
        // } else if(arr.length === 3 || arr.length === 4) {
        //     $('.'+el+' .other .first').append("<div class='weui-flex__item'><img src="+arr[0].imageUrl+" style='width:100%;'></div>");
        //     for(var i = 1;i < arr.length; i++) {
        //         $('.'+el+' .other .second').append("<div class='weui-flex__item'><img src="+arr[i].imageUrl+" style='width:99%;margin-left:1%;'></div>");
        //     }
        // } else {
        //     $('.'+el+' .other .first').append("<div class='weui-flex__item'><img src="+arr[0].imageUrl+" style='width:99%;'></div><div class='weui-flex__item'><img src="+arr[0].imageUrl+" style='width:99%;margin-left:1%;'></div>");
        //     for(var j = 1;j < arr.length; j++) {
        //         $('.'+el+' .other .second').append("<div class='weui-flex__item'><img src="+arr[j].imageUrl+" style='width:99%;margin-left:1%;'></div>");
        //     }
        // }
    }else {
        $('.'+el).css('display', 'none');
        $('.'+el+" .song").empty();
        $('.'+el+" .first").empty();
        $('.'+el+" .other").empty();
    };
};

function tempAdd(obj, index, percent, mr) {
    mr = mr === undefined ? 0 : mr;
    if(obj.mediaType === 'picture') {
        return "<img data-index="+index+" src="+obj.imageUrl+" style='width:"+percent+";margin-right:"+mr+";'>";
    }else {
        return "<video data-index="+index+" style='width:"+percent+";height: 100%;object-fit: fill;margin-right: "+mr+";'><source src="+obj.videoUrl+" type=' video/mp4'><source src="+obj.videoUrl+" type='video/ogg'></video>";
    }
}

function timeChange(time) {
    var timestamp1 = Date.parse(new Date());
    var timestamp2 = Date.parse(time.replace(/-/g, "/"));
    if((timestamp1 - timestamp2) > 86400000) {
        return time;
    }else if( 8640000 >= (timestamp1 - timestamp2) && (timestamp1 - timestamp2) > 3600000) {
        return Math.floor((timestamp1 - timestamp2)/3600)+"小时前"
    }else if( 3600000 >= (timestamp1 - timestamp2) && (timestamp1 - timestamp2) > 60000) {
        return Math.floor((timestamp1 - timestamp2)/60000)+"分钟前"
    }else{
        return '刚刚'
    }
}
